package com.zbkj.client.task;

import cn.hutool.core.lang.TypeReference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zbkj.client.config.WebSocketSessionManager;
import com.zbkj.client.enums.WebSocketEventType;
import com.zbkj.client.service.AgentClientService;
import com.zbkj.client.service.ClientLoginService;
import com.zbkj.common.model.client.workbench.VideoSplit;
import com.zbkj.common.model.client.workbench.VideoSubtitle;
import com.zbkj.service.service.VideoSplitService;
import com.zbkj.service.service.VideoSubtitleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class VideoSubtitleUpdateStatusTask {
    @Autowired
    private VideoSubtitleService videoSubtitleService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private ThreadPoolTaskScheduler taskScheduler;

    @Autowired
    private WebSocketSessionManager webSocketSessionManager;

    @Autowired
    private AgentClientService agentClientService;

    @Autowired
    private ClientLoginService clientLoginService;

    @Value("${workbench.video-split}")
    private String videoSplitBaseUrl;

    private final String videoSubtitleInfoUrl = "/api/v1/video/subtitle/status";
    private final String videoSubtitleInfoUrlNew = "/api/v1/video/split/status";
    private final ObjectMapper objectMapper = new ObjectMapper();

    public void start(String linkId) {
        scheduleTask(linkId, 0, 5);
    }

    private void scheduleTask(String linkId, int retry, int maxRetry) {
        long delay = retry == 0 ? 2 * 60 * 1000 : 60 * 1000; // 第一次2分钟，后面1分钟
        taskScheduler.schedule(() -> run(linkId, retry, maxRetry), new Date(System.currentTimeMillis() + delay));
    }

    private void run(String linkId, int retry, int maxRetry) {
        VideoSubtitle videoSubtitle = videoSubtitleService.getOne(new LambdaQueryWrapper<VideoSubtitle>().eq(VideoSubtitle::getLinkId, linkId));
        if (videoSubtitle == null) {
            log.warn("未找到视频字幕的记录，linkId={}", linkId);
            return;
        }
        if (videoSubtitle.getIsDel() != null && videoSubtitle.getIsDel() == 1) {
            log.info("视频拆解记录已删除，linkId={}", linkId);
            return;
        }
        if (videoSubtitle.getStatus() != null && videoSubtitle.getStatus() != 1) {
            //扣点
            clientLoginService.updateMerPoint(videoSubtitle.getUserId(),
                    videoSubtitle.getMerId(),
                    "videoSubtitle",
                    videoSubtitle.getId(),
                    agentClientService.getMouleName("videoSubtitle"),
                    videoSubtitle.getTitle(),
                    agentClientService.getPointByDuration("videoSubtitle", videoSubtitle.getDuration()),
                    videoSubtitle.getDuration()
            );

            log.info("视频转字幕状态已更新，linkId={}", linkId);
            return;
        }

        // 确定事件名称
        String eventName="";

        String url = videoSplitBaseUrl + videoSubtitleInfoUrlNew + "/" + linkId;
        try {
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
            JsonNode root = objectMapper.readTree(response.getBody());
            boolean success = root.path("success").asBoolean();
            JsonNode result = root.path("data").path("Data");
            String taskStatus = result.path("Status").asText();
            if (success && "PROCESS_SUCCESS".equals(taskStatus)) {
                // 更新分析结果
                String event = result.path("Result").asText();
                Map<String, Object> map = JSON.parseObject(event, Map.class);

                videoSubtitle.setVideoSubtitle(map);
//                videoSubtitle.setTitle(title);
                videoSubtitle.setStatus(2);
                videoSubtitle.setUpdateTime(new Date());
                videoSubtitleService.updateById(videoSubtitle);
                log.info("视频转字幕任务完成，linkId={}", linkId);

                eventName = WebSocketEventType.AddVideoSubtitleSuccess.name();

                //扣点
                clientLoginService.updateMerPoint(videoSubtitle.getUserId(),
                        videoSubtitle.getMerId(),
                        "videoSubtitle",
                        videoSubtitle.getId(),
                        "视频转文案",
                        videoSubtitle.getTitle(),
                        agentClientService.getPointByDuration("videoSubtitle", videoSubtitle.getDuration()),
                        videoSubtitle.getDuration()
                );


            } else if (success && retry < maxRetry - 1) {
                log.info("视频转字幕未完成，linkId={}, retry={}", linkId, retry + 1);
                scheduleTask(linkId, retry + 1, maxRetry);
            } else if (!success && "PROCESS_FAILED".equals(taskStatus)) {
                String errorMessage = result.path("ErrorMessage").asText();
                log.info("视频转字幕失败，linkId={}, 原因为：{}", linkId, errorMessage);
                videoSubtitle.setStatus(3);
                videoSubtitle.setErrMsg(errorMessage);
                videoSubtitle.setUpdateTime(new Date());
                videoSubtitleService.updateById(videoSubtitle);
                //推送ws事件名称
                eventName = WebSocketEventType.AddVideoSubtitleFail.name();
            } else if (!success) {
                String message = root.path("message").asText();
                String errorMessage = message != null ? message: "视频转字幕失败";
                log.info("视频转字幕失败，linkId={}, 原因为：{}", linkId, errorMessage);
                videoSubtitle.setStatus(3);
                videoSubtitle.setErrMsg(errorMessage);
                videoSubtitle.setUpdateTime(new Date());
                videoSubtitleService.updateById(videoSubtitle);
                //推送ws事件名称
                eventName = WebSocketEventType.AddVideoSubtitleFail.name();
            }else {
                videoSubtitle.setStatus(3);
                videoSubtitle.setErrMsg("视频转字幕任务失败");
                videoSubtitle.setUpdateTime(new Date());
                videoSubtitleService.updateById(videoSubtitle);
                //推送ws事件名称
                eventName = WebSocketEventType.AddVideoSubtitleFail.name();

                log.warn("视频转字幕任务未完成或重试次数已达上限，linkId={}, retry={}", linkId, retry + 1);
                return;
            }


            // 推送WebSocket消息给前端
            Integer userId = videoSubtitle.getUserId();
            if (userId != null) {
                Map<String, Object> data = new HashMap<>();
                data.put("id", videoSubtitle.getId());
                data.put("linkId", videoSubtitle.getLinkId());
                data.put("status", videoSubtitle.getStatus());

                Map<String, Object> message = new HashMap<>();
                message.put("event", eventName);
                message.put("data", data);

                String jsonMessage = JSON.toJSONString(message);
                webSocketSessionManager.sendMessageToUser(userId, jsonMessage);
                log.info("向用户 {} 推送视频转文案状态更新: {}", userId, jsonMessage);
            }

        } catch (Exception e) {
            videoSubtitle.setStatus(3);
            videoSubtitle.setErrMsg("频转字幕状态查询异常");
            videoSubtitle.setUpdateTime(new Date());
            videoSubtitleService.updateById(videoSubtitle);

            log.error("视频转字幕状态查询异常，linkId={}", linkId, e);
        }
    }
} 